

#include "../include/ring_buffer.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void ring_buffer_init(ring_buffer_t *buffer, int length)
{
	buffer->length = length + 1;
	buffer->start = buffer->end = 0;
	buffer->buffer = (unsigned char *)malloc(buffer->length * sizeof(char));
}


void ring_buffer_destroy(ring_buffer_t *buffer)
{
	if (buffer)
	{
		free(buffer->buffer);
		free(buffer);
		buffer = NULL;
	}
}

int ring_buffer_write(ring_buffer_t *buffer, const char *src, int length)
{
	if (ring_buffer_available_data(buffer) == 0)
		buffer->start = buffer->end = 0;

	if (length > ring_buffer_available_space(buffer))
	{
		fprintf(stdout, "not enought space\n");
		return -1;
	}

	void *ret = memcpy(ring_buffer_ends_at(buffer), src, length);
	if (!ret)
		return -1;

	ring_buffer_commit_write(buffer, length);

	return length;
}

int ring_buffer_read(ring_buffer_t *buffer, char *dest, int amount)
{
	if (amount > ring_buffer_available_data(buffer))
	{
		fprintf(stdout, "not enought data\n");
		return -1;
	}

	void *ret = memcpy(dest, ring_buffer_starts_at(buffer), amount);
	if (!ret)
		return -1;

	ring_buffer_commit_read(buffer, amount);
	if (buffer->end == buffer->start)
		buffer->start = buffer->end = 0;

	return amount;
}
